#!/usr/bin/lua

local socket = require("socket")

function receive (connection)
    connection:settimeout(0)
    local s, status, partial = connection:receive(1024)
    if status == "timeout" then
        coroutine.yield(connection)
    end
    return s or partial, status
end

function download (host, file)
    -- 创建一个 TCP 连接，连接到 HTTP 连接的标准端口 -- 80 端口上
    local sock = assert(socket.connect(host, 80))
    local count = 0
    sock:send("GET " .. file .. " HTTP/1.0\r\n\r\n")
    while true do
        -- 以 1K 的字节块来接收数据，并把接收到字节块输出来
        local s, status, partial = sock:receive(1024)
        count = count + #(s or partial)
        if status == "closed" then break end
    end
        sock:close()
        print(file, count)
end

threads = {}

function get (host, file)
    local co = coroutine.create(function()
        download(host, file)
    end)

    table.insert(threads, co)
end

function dispatch ()
    local i = 1
    local connections = {}
    while true do
        if threads[i] == nil then
            if threads[1] == nil then break end
            i = 1
            connections = {}
        end
        local status, res = coroutine.resume(threads[i])
        if not res then
            table.remove(threads, i)
        else
            i = i + 1
            connections[#connections + 1] = res
            if #connections == #threads then
                socket.select(connections)
            end
        end
    end
end

host = "www.w3.org"

get(host, "/TR/html401/html40.txt")
get(host, "/TR/2002/REC-xhtml1-20020801/xhtml1.pdf")
get(host, "/TR/REC-html32.html")
get(host, "/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt")

dispatch() -- main loop
